<template>
    <div class="app-container">
        <!-- 区域筛选 -->
        <area-addr :addrIds="ft_data" :allSelectOpt="true"></area-addr>
        <el-row :gutter="20">
            <el-col :xs="24" :sm="12" :md="6" :lg="6">
                <div class="grid-content bg-purple-light">
                    <el-button @click="getEptRoomInfos('all')">筛选结果</el-button>
                </div>
            </el-col>
        </el-row>
        <el-row :gutter="20">
            <el-col :xs="24" :sm="9" :md="7" :lg="5">
                <div class="grid-content bg-purple">
                    <el-input v-model="searchMsg" placeholder="请输入机房名称"></el-input>
                </div>
            </el-col>
            <el-col :xs="12" :sm="10" :md="10" :lg="10">
                <div class="grid-content bg-purple-light">
                    <el-button type="primary" icon="search" @click="getEptRoomInfos('search')">搜索</el-button>
                </div>
            </el-col>
            <el-col :xs="12" :sm="5" :md="7" :lg="9">
                <div class="grid-content bg-purple-light" style="float:right">
                    <el-button icon="edit" @click="createEptRoom()">新建机房</el-button>
                </div>
            </el-col>
        </el-row>
        <!-- 机房信息表 -->
        <el-table :data="infos.pageData" v-loading.body="listLoading" element-loading-text="加载中..." border style="width: 100%;margin:20px 0">
            <el-table-column label="序号" min-width="50px">
                <template scope="scope">
                    <span>{{ scope.$index+1+(pageConfig.curPage-1)*pageConfig.size }}</span>
                </template>
            </el-table-column>
            <el-table-column label="所处地域" min-width="180px">
                <template scope="scope">
                    <span>{{ scope.row.areaName+'-'+scope.row.countryName+'-'+scope.row.provinceName+'-'+scope.row.cityName}}</span>
                </template>
            </el-table-column>
            <el-table-column label="机房名称" min-width="130px">
                <template scope="scope">
                    <span>{{scope.row.roomName}}</span>
                </template>
            </el-table-column>
            <el-table-column label="详细地址" min-width="220px">
                <template scope="scope">
                    <span>{{ scope.row.addr }}</span>
                </template>
            </el-table-column>
            <el-table-column label="机房类型" min-width="120px">
                <template scope="scope">
                    <span>{{ scope.row.roomTypeName }}</span>
                </template>
            </el-table-column>
            <el-table-column label="负责人" min-width="100px">
                <template scope="scope">
                    <span>{{ scope.row.contactPerson }}</span>
                </template>
            </el-table-column>
            <el-table-column label="联系电话" min-width="130px">
                <template scope="scope">
                    <span>{{ scope.row.contactPhone }}</span>
                </template>
            </el-table-column>
            <el-table-column label="操作" min-width="160px">
                <template scope="scope">
                    <el-button size="small" type="success" @click="editEptRoom(scope.row)">编辑</el-button>
                    <el-button size="small" type="danger" @click="deleteConfirm(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页条 -->
        <div class="block">
            <el-pagination style="padding:0;" @current-change="handleCurrentChange" :current-page.sync="pageConfig.curPage" :page-size="pageConfig.size" layout="total, prev, pager, next, jumper" :total="pageConfig.total">
            </el-pagination>
        </div>
        <!-- dialog编辑框 -->
        <el-dialog title="机房信息" size="small" :visible.sync="eptRoomEditVisible">
            <el-form :model="eptRoomInfos" style="margin-bottom:-30px" :rules="rules" ref="eptRoomInfos" v-if="eptRoomEditVisible">
                <el-form-item label="所属区域" :label-width="formLabelWidth" required>
                    <area-addr :style="inputWidth" :addrIds="eptRoomInfos" @updates="changedData" :validator="true" ref="getFunc"></area-addr>
                </el-form-item>
                <el-form-item label="机房名称" :label-width="formLabelWidth" prop="roomName">
                    <el-input v-model="eptRoomInfos.roomName" auto-complete="off" :style="inputWidth" placeholder="请输入机房名称"></el-input>
                </el-form-item>
                <el-form-item label="机房地址" :label-width="formLabelWidth" prop="addr">
                    <el-input v-model="eptRoomInfos.addr" auto-complete="off" :style="inputWidth" placeholder="请输入机房地址"></el-input>
                </el-form-item>
                <el-form-item label="负责人" :label-width="formLabelWidth" prop="contactPerson">
                    <el-input v-model="eptRoomInfos.contactPerson" auto-complete="off" :style="inputWidth" placeholder="请输入负责人"></el-input>
                </el-form-item>
                <el-form-item label="联系电话" :label-width="formLabelWidth" prop="contactPhone" required>
                    <el-input v-model.number="eptRoomInfos.contactPhone" auto-complete="off" :style="inputWidth" placeholder="请输入联系电话"></el-input>
                </el-form-item>
                <el-form-item label="机房类型" :label-width="formLabelWidth" prop="roomType">
                    <el-select v-model="eptRoomInfos.roomType" placeholder="请选择机房类型" :style="inputWidth">
                        <el-option v-for="list in roomTypeDatas" :key="list.dictKey" :label="list.dictValue" :value="list.dictKey"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="机房状态" :label-width="formLabelWidth" prop="roomState">
                    <el-select v-model="eptRoomInfos.roomState" placeholder="请选择机房状态" :style="inputWidth">
                        <el-option label="正常" value="1"></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="eptRoomEditVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitForm('eptRoomInfos',eptRoomInfos.type)">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<style>
.el-row {
    margin-bottom: 20px;
}

.el-row:last-child {
    margin-bottom: 0;
}
</style>
<script>
import areaAddr from '@/components/Area-addr';
export default {
    components: {
        areaAddr
    },
    data() {
        // 菜单格式及是否存在的判断
        var existPhone = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请输入联系电话'));
            } else {
                if (!Number.isInteger(value)) {
                    callback(new Error('请输入数字值'));
                } else {
                    if (value.toString().length < 7 || value.toString().length > 15) {
                        callback(new Error('长度在不超过 15 个字符'));
                    } else {
                        callback()
                    }
                }
            }
        };
        return {
            listLoading: true,
            inputWidth: { width: '96%' },
            formLabelWidth: '100px',
            // 机房类型列表信息
            roomTypeDatas: [],
            // 机房信息
            infos: {
                tableData: [],
                re_tableData: [],
                pageData: []
            },
            // 模态框状态
            eptRoomEditVisible: false,
            // 编辑机房信息
            eptRoomInfos: {},
            //分页配置
            pageConfig: {
                curPage: 1,
                total: null,
                size: 9,
            },
            rules: {
                roomName: [
                    { required: true, message: '请输入机房名称', trigger: 'blur' },
                    { min: 1, max: 25, message: '长度在不超过 25 个字符', trigger: 'blur' }
                ],
                addr: [
                    { required: true, message: '请输入机房地址', trigger: 'blur' },
                    { min: 1, max: 120, message: '长度在不超过 120 个字符', trigger: 'blur' }
                ],
                contactPerson: [
                    { required: true, message: '请输入负责人', trigger: 'blur' },
                    { min: 1, max: 20, message: '长度在不超过 20 个字符', trigger: 'blur' }
                ],
                contactPhone: [
                    { validator: existPhone, trigger: 'blur' }
                ],
                roomType: [
                    { required: true, message: '请选择机房类型', trigger: 'change' }
                ],
                roomState: [
                    { required: true, message: '请选择机房状态', trigger: 'change' }
                ]
            },
            // 筛选用区域信息
            ft_data: {
                areaId: '',
                countryId: '',
                provinceId: '',
                cityId: ''
            },
            // 筛选条件
            searchMsg:'',
            latestData: null
        }
    },
    created() {
        // 当前页面table展示信息
        this.getEptRoomInfos('all');
        // 机房信息类型列表
        this.getRoomTypeLists();
    },
    methods: {
        getEptRoomInfos(type) {
            let are = this.ft_data.areaId < 1 ? '0' : this.ft_data.areaId;
            let cou = this.ft_data.countryId < 1 ? '0' : this.ft_data.countryId;
            let pro = this.ft_data.provinceId < 1 ? '0' : this.ft_data.provinceId;
            let cit = this.ft_data.cityId < 1 ? '0' : this.ft_data.cityId;
            this.listLoading = true;
            let _url =  '/sys/room/list/' + are + '/' + cou + '/' + pro + '/' + cit;
            this.$http.get(_url)
                .then((response) => {
                    if (response.code === 0) {
                        if (type === 'all') {
                            this.searchMsg = '';
                            this.infos.tableData = this.infos.re_tableData = response.data;
                        } else {
                            this.infos.tableData = this.infos.re_tableData = response.data.filter(item => {
                                return item.roomName.indexOf(this.searchMsg) > -1
                            })
                        }
                        this.listLoading = false;
                        this.pageConfig.total = this.infos.re_tableData.length;
                        this.pageChange(this.pageConfig.curPage);
                    } else {
                        this.listLoading = false;
                        console.log(response.statusText)
                    }
                }).catch((response) => {
                    setTimeout(() => {
                        this.listLoading = false;
                    }, 400);
                    console.log(response)
                })
        },
        // 创建机房信息
        createEptRoom() {
            this.resetForm();
            this.eptRoomInfos.type = 'new';
            this.eptRoomEditVisible = true;
        },
        // 编辑机房信息
        editEptRoom(info) {
            this.resetForm();
            info.contactPhone = Number(info.contactPhone);
            this.latestData = JSON.parse(JSON.stringify(info));
            this.eptRoomEditVisible = true;
        },
        changedData() {
            this.eptRoomInfos = this.latestData;
        },
        // 机房类型列表
        getRoomTypeLists() {
            let _url = '/sys/dictionary/listById/room_type';
            this.$http.get(_url)
                .then((response) => {
                    if (response.code === 0) {
                        this.roomTypeDatas = response.data;
                    } else {
                        console.log(response.statusText)
                    }
                }).catch((response) => {
                    console.log(response)
                })
        },
        // 机房信息提交
        submitForm(formName, type) {
            let _url = '';
            if (!this.$refs.getFunc.validate()) { return }
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    if (type === 'new') {
                        _url += '/sys/room/add';
                        this.$http.post(_url, this.eptRoomInfos)
                            .then((response) => {
                                if (response.code === 0) {
                                    this.eptRoomEditVisible = false;
                                    this.getEptRoomInfos();
                                    this.showMessage('创建成功!', 'success');
                                } else {
                                    this.showWarning(response.msg, '创建失败');
                                }
                            }).catch((response) => {
                                console.log(response)
                            })
                    } else {
                        _url += '/sys/room/update';
                        this.$http.put(_url, this.eptRoomInfos)
                            .then((response) => {
                                if (response.code === 0) {
                                    this.eptRoomEditVisible = false;
                                    this.getEptRoomInfos();
                                    this.showMessage('修改成功!', 'success');
                                } else {
                                    this.showWarning(response.msg, '修改失败');
                                }
                            }).catch((response) => {
                                console.log(response)
                            })
                    }
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        // 删除机房相关操作
        deleteConfirm(info) {
            const h = this.$createElement;
            this.$msgbox({
                title: '删除机房',
                message: h('p', null, [
                    h('span', null, '是否删除 '),
                    h('span', { style: 'color: #20A0FF;font-size:1.2em;font-weight:bold' }, info.roomName),
                    h('span', null, ' 这个机房？'),
                ]),
                type: 'warning',
                showCancelButton: true,
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                beforeClose: (action, instance, done) => {
                    if (action === 'confirm') {
                        instance.confirmButtonLoading = true;
                        instance.confirmButtonText = '删除中...';
                        setTimeout(() => {
                            done();
                            setTimeout(() => {
                                instance.confirmButtonLoading = false;
                            }, 100);
                        }, 400);
                    } else {
                        done();
                    }
                }
            }).then((action) => {
                if (action === 'confirm') {
                    this.eptRoomDelete(info.roomId);
                } else {
                    showMessage('已取消删除', 'info');
                }
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        eptRoomDelete(roomId) {
            let _url = '/sys/room/delete/' + roomId;
            this.$http.delete(_url).then((response) => {
                if (response.code === 0) {
                    this.getEptRoomInfos();
                    this.showMessage('删除成功!', 'success');
                } else {
                    if (response.code === -1) {
                        console.log(response.statusText);
                    } else {
                        this.showWarning(response.msg, '删除失败');
                    }
                }
            }).catch((response) => {
                console.log(response)
            })
        },
        // 分页按钮
        handleCurrentChange(val) {
            this.pageConfig.curPage = val;
            this.pageChange(val);
        },
        // 分页
        pageChange(page) {
            this.infos.pageData = this.infos.re_tableData.slice((page - 1) * this.pageConfig.size, page * this.pageConfig.size);
        },
        showMessage(msg, type) {
            this.$message({
                message: msg,
                type: type
            });
        },
        showWarning(msg, title) {
            this.$alert(msg, title, {
                showConfirmButton: false,
                showCancelButton: true,
                cancelButtonText: '关闭',
            });
        },
        // 初始化
        resetForm() {
            this.latestData = this.eptRoomInfos = {
                areaId: '',
                countryId: '',
                provinceId: '',
                cityId: '',
                cityName: '',
                areaName: '',
                countryName: '',
                provinceName: '',
                roomName: '',
                addr: '',
                contactPerson: '',
                contactPhone: '',
                roomType: '',
                roomState: '',
                type: ''
            };
        },
    }
}
</script>